﻿var mysql = require('../DataAccess/mysqlDA.js');

exports.index = function () {
    this.render('douban/index.html', { msg: 'Hello World' });
};

exports.sc = function () {
    this.render('douban/sc.html');
};

exports.top250 = function () {
    var _t = this;
    mysql.excute('SELECT * FROM test.top250', [], function (json) {
        _t.renderJson(json);
    });
};

var http = require('http'),
    events = require("events"),
    DOUBAN = require("../static/js/api-parser.js").DOUBAN;


//创建一个EventEmitter的实例
var tweets_emitter = new events.EventEmitter();

exports.Collection = function (params) {

    var _t = this;
    //注册一个一次性的事件监听
    var listener = tweets_emitter.once("tweets", function (json) {
        _t.renderJson(json);
    });

    var from = 1, count = 10;
    if (params) {
        from = params.from || 1;
        count = params.count || 10;
    }

    httpReq.get("/people/2477477/collection?cat=movie&status=watched&alt=json&start-index="
    + from
    + "&max-results="
    + count, function (data) {

        var tweets = JSON.parse(data);

        var entries = DOUBAN.parseMultiCollection(tweets).entries;
        for (var i = 0; i < entries.length; i++) {
            mysql.InsertDoubanM(entries[i]);
        }

        tweets_emitter.emit("tweets", tweets);
    });
};

exports.sql = function () {
    var _t = this;
    mysql.excute('call mySP(?,?,?)', ['1','aa',33], function (json) {
        _t.renderJson(json);
    });
}

exports.update = function (params) {
    var id = params.id;

    var _t = this;
    //注册一个一次性的事件监听
    var listener = tweets_emitter.once("tweets", function (json) {
        _t.renderJson(json);
    });

    httpReq.get("/collection/" + id + '?alt=json', function (data) {

        var tweets = JSON.parse(data);

        var data = DOUBAN.parseCollection(tweets);

        mysql.InsertDoubanM(data);

        tweets_emitter.emit("tweets", tweets);
    });
}

var tdouban_client = http.createClient(80, "api.douban.com");

var httpReq = {
    get: function (url, onDataLoaded) {
        var request = tdouban_client.request("GET", url);

        request.addListener("response", function (response) {
            var body = "";
            response.addListener("data", function (data) {
                body += data;
            });

            response.addListener("end", function () {
                onDataLoaded(body);
            });
        });

        request.end();
    }
}